
/**
 * 定时器
 */
const logger = require('./util').logger

const tasks = new Map()

/**
 * @name 定时器名
 * @begin 开始时间
 * @cycle 周期，单位：ms
 * @begin 开始日期
 */
const addTask = ({name, begin, cycle, fun, args}) => {
  if (tasks.has(name)) {
    throw new Error(`任务 ${name} 已经存在！`)
  }
  logger.info(`添加定时任务 name=${name}, begin=${begin}, cycle=${cycle}`)
  if (cycle && fun){
    tasks.set(name, {
      begin: begin ? begin.getTime() : new Date().getTime() + 1000,
      cycle, fun, args
    });
    startTask(name)
  }
}

const removeTask = (name) => {
  if (tasks.has(name)) {
    logger.debug(`删除任务 ${name}`)
    stopTask(name)
    tasks.delete(name)
  }
}

const stopTask = (name) => {
  if (tasks.has(name)) {
    let t = tasks.get(name)
    logger.debug(`停止任务 ${name} , is run ${t.isRun}`)
    if (t.isRun) {
      clearInterval(t.id)
    } else {
      clearTimeout(t.id)
    }
    t.id = undefined
  }
}

const startTask = (name) => {
  // return
  if (!tasks.has(name)) {
    throw new Error(`${name} 定时任务不存在`)
  }
  let t = tasks.get(name)
  if (!t.id) {
    logger.debug(`开始启动任务 ${name}`)
    let now = new Date().getTime()
    if (t.begin < now) {  
      t.begin += Math.ceil((now - t.begin) / t.cycle) * t.cycle
    }
    t.id = setTimeout((_t) => {
      //设置循环
      _t.id = setInterval(_t.fun, _t.cycle, _t.args)
      _t.isRun = true;
      logger.debug(`开始运行任务 ${name}`)
      _t.fun(_t.args)   //运行一次
    }, t.begin - now, t)
    t.isRun = false
  }
}

module.exports = {
  addTask, stopTask, startTask, removeTask
}